package cn.piggy.gateway.core.datasource.connection;

import cn.piggy.gateway.core.client.NettyClient;
import cn.piggy.gateway.core.client.Request;
import cn.piggy.gateway.core.common.CommonUtil;
import cn.piggy.gateway.core.http.HttpStatement;

import java.util.LinkedList;
import java.util.Map;


public class PiggyConnection implements Connection {
    private String application;
    private String address;

    public PiggyConnection(String application,LinkedList<String> list){
        this.application = application;
        this.address = CommonUtil.getAddress(list);
        NettyClient.init(this.application, this.address);
    }


    @Override
    public Object execute(HttpStatement httpStatement, Map<String, Object> params) {
        try {
            String methodName = httpStatement.getInterfaceName() + "." + httpStatement.getMethodName();
            String parameterType = httpStatement.getParameterType();
            String parameterName = httpStatement.getParameterName();
            Request request = new Request();
            request.setPath(methodName);
            Object[] args = null;
            if(!"".equals(parameterType)){
                args = CommonUtil.getParams(parameterName, params, parameterType);
            }
            request.setParam(args);
            return NettyClient.sendRequest(application, address, request);
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }


}
